import { Form, Input, Button, Checkbox, message } from "antd";
import { useNavigate } from "react-router-dom";
import { setRememberAccount, setToken } from "@store/constants"
import { mockToken } from "@util/index"
import { useSelector, shallowEqual, useDispatch } from "react-redux"
import { useStoreState } from "@hooks/index"
import "./Login.scss"


const Login: React.FC = memo(function (props: {}) {
  const navigate = useNavigate()
  const dispatcher = useDispatch()
  const { rememberAccount } = useStoreState("rememberAccount")

  const onFinish = (vals: { remember: boolean, account: string, pwd: string }) => {
    if (vals.account === "admin" && vals.pwd === "123456") {
      message
        .loading('登录中...', 0.5)
        .then(() => {
          // 记住账号密码
          dispatcher(setRememberAccount(vals.remember))
          dispatcher(setToken(mockToken()))
          message.success('登录成功', 0.5, () => {
            navigate("/")
          });
        })
    }
  };
  const onFinishFailed = () => { message.error('请输入正确的用户名和密码'); };

  return (
    <div className="login-page">
      <h1>React 后台管理</h1>
      <p>欢迎使用, 请先登录</p>
      <Form className="login-form" initialValues={
        { remember: rememberAccount, account: rememberAccount ? "admin" : "", pwd: rememberAccount ? "123456" : "" }
      } onFinish={onFinish} onFinishFailed={onFinishFailed}>
        <Form.Item name="account" rules={[{ required: true, message: 'Please input your username!' }]}>
          <Input placeholder="账号: admin" />
        </Form.Item>
        <Form.Item name="pwd" rules={[{ required: true, message: 'Please input your password!' }]}>
          <Input.Password placeholder="密码: 123456" />
        </Form.Item>
        <Form.Item>
          <Form.Item name="remember" valuePropName="checked" noStyle>
            <Checkbox>记住我</Checkbox>
          </Form.Item>
        </Form.Item>
        <Form.Item className="btns">
          <Button type="primary" htmlType="submit">登录</Button>
        </Form.Item>
      </Form>
    </div>
  )
})

export default Login;
